import cgi
import datetime
import wsgiref.handlers
import os

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

class Blog(db.Model):
  author=db.UserProperty()
  content=db.StringProperty(multiline=True)
  date=db.DateTimeProperty(auto_now_add=True)

class UserInfo(db.Model):
  username=db.StringProperty()
  color=db.StringProperty()

class MainPage(webapp.RequestHandler):
  def get(self):
    blogs=db.GqlQuery("SELECT * "
                      "FROM Blog " 
                      "ORDER BY date DESC")
    #check if user have right to see write button
    usr=users.get_current_user()
    haveWriteRights=False
    if usr and CheckUserRights(usr.nickname()):
    #if usr=='fanweixiao':
      haveWriteRights=True

    template_values={
      'blogs': blogs,
      'loginUrl': users.create_login_url(self.request.uri),
      'logoutUrl': users.create_logout_url('/'),
      'haveWriteRights': haveWriteRights,
      'usr': usr
    }

    path=os.path.join(os.path.dirname(__file__), 'templates/index.html')
    self.response.out.write(template.render(path, template_values))

class WriteBlog(webapp.RequestHandler):
  def post(self):
    blog=Blog()
    tmpUsr=users.get_current_user().nickname()
    if tmpUsr and CheckUserRights(tmpUsr)==True :
      blog.author=users.get_current_user()
      blog.content=self.request.get('content')
      if blog.content:
        blog.put()
        self.redirect('/')
      else:
        self.response.out.write('You must write something!')
    else:
      self.response.out.write('you don\'t have permission')

def CheckUserRights(username):
  if not username:
    return False
  if username=='fanweixiao' or username=='weiyixie' or username=='hongxiaojun' or username=='hanfeiz':
    return True
  else:
    return False

def main():
  application=webapp.WSGIApplication([
    ('/', MainPage),
    ('/writeblog', WriteBlog),
  ], debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
